<?php

namespace app\user\controller\group_activity\list;

use app\admin\service\UserService;
use app\BaseController;
use app\model\ConfigModel;
use app\model\group_activity\GroupActivityTaskDepartmentModel;
use app\model\group_activity\GroupActivityTaskModel;
use app\model\group_activity\GroupActivityTaskUserModel;
use app\model\group_activity\GroupActivityTaskUserResultModel;
use app\user\service\GroupActivityService;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 活动报名列表
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require',
            ]);
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['type_id'])) {
                $where[] = ['type_id', '=', $param['type_id']];
            }
            if (!empty($param['status'])) {
                $where[] = ['status', '=', $param['status']];
            }
            if (!empty($param['uid'])) {
                $where[] = ['uid', '=', $param['uid']];
            }
            $GroupActivityTaskDepartmentModel = new GroupActivityTaskDepartmentModel();
            $task_id = $GroupActivityTaskDepartmentModel->where('department_id','=',$this->userData['department_id'])->column('task_id');
            if (!empty($task_id)) {
                $where[] = ['id','in',$task_id];
            }else{
                $where[] = ['id','=',-1];
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $data = $GroupActivityTaskModel->where($where)->with([
                'user' => function ($query) {
                    $query->with(['roleName']);
                },
                'typeName'
            ])->order('id','desc')->paginate($param['pageSize'])->toArray();
            if (!empty($data['data'])){
                $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
                foreach ($data['data'] as &$item){
                    if (empty($item['role_name'])){
                        $item['role_name'] = '超级管理员';
                    }
                    $log = $GroupActivityTaskUserModel->where([
                        ['task_id','=',$item['id']],
                        ['uid','=',$this->userData['id']],
                        ['audit_status','in',[1,2]]
                    ])->value('id');
                    $item['is_bm'] = $log?1:0;
                }
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $info = $GroupActivityTaskModel->with([
                'user' => function($query){
                    $query->with(['roleName']);
                },
                'typeName',
                'taskRatingScale' => function($query){
                    $query->with(['RatingScale']);
                },
                'taskDepartment'
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            if (!empty($info['taskDepartment'])){
                $UserService = new UserService($this->app);
                $DepartmentData = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($info['taskDepartment'] as &$value) {
                    $value['department_name'] = $DepartmentData[$value['department_id']]['all_name']??'--';
                }
            }
            if (!empty($info['taskRatingScale'])){
                $GroupActivityTaskUserResultModel = new GroupActivityTaskUserResultModel();
                $ResultList = $GroupActivityTaskUserResultModel->where([
                    ['task_id','=',$param['id']],
                    ['uid','=',$this->userData['id']],
                    ['task_user_id','=',0]
                ])->field('id,rating_scale_id')->select()->toArray();
                $ResultData = [];
                foreach ($ResultList as $v){
                    $ResultData[$v['rating_scale_id']] = $v['id'];
                }
                foreach ($info['taskRatingScale'] as &$value) {
                    $value['result_id'] = $ResultData[$value['rating_scale_id']]??0;
                }
            }
            $info['role_name'] = $info['role_name']??'超级管理员';
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 报名
     * @return bool|string
     */
    public function signUp(): bool|string
    {
        $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
        $GroupActivityTaskUserModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['key','=','group_activity']
            ])->value('value')??'';
            $config = json_decode($config,true);
            if (empty($config['is_repeat']) || $config['is_repeat'] == 0) {
                //不允许重复报名
                $is_repeat = $GroupActivityTaskUserModel->where([
                    ['uid','=',$this->userData['id']],
                    ['task_id','=',$param['id']],
                ])->value('id');
                if ($is_repeat) throw new \Exception('不可重复报名！');
            }else{
                //允许重复报名
                $is_repeat = $GroupActivityTaskUserModel->where([
                    ['uid','=',$this->userData['id']],
                    ['task_id','=',$param['id']],
                    ['audit_status','in',[1,2]]
                ])->value('id');
                if ($is_repeat) throw new \Exception('存在已报名或报名中的记录，请勿重复操作！');
            }
            $addData = [
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],
                'task_id' => $param['id'],
                'time' => time()
            ];
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $taskInfo = $GroupActivityTaskModel->find($param['id']);
            if ($taskInfo['status'] != 2) throw new \Exception('不在报名阶段，无法报名');
            if ($taskInfo['enroll_review'] == 0){
                //不需要审核
                $addData['audit_status'] = 2;
                //自增报名人数
                $taskInfo->inc('enroll_num')->save();
            }
            $task_user_id = $GroupActivityTaskUserModel->insertGetId($addData);
            //绑定测评结果
            if (!empty($param['result_id'])){
                $GroupActivityTaskUserResultModel = new GroupActivityTaskUserResultModel();
                $GroupActivityTaskUserResultModel->where('id','in',$param['result_id'])->update([
                    'task_user_id' => $task_user_id
                ]);
            }
            $GroupActivityTaskUserModel->commit();
            return success();
        } catch (\Exception $e) {
            $GroupActivityTaskUserModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 提交任务测评结果
     * @return false|string
     */
    public function submitTaskEvaluationResults(): bool|string
    {
        $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
        $GroupActivityTaskUserModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'task_id|任务ID' =>  'require',
//                'task_user_id|用户任务表ID' =>  'require',
                'rating_scale_id|量表ID' =>  'require',
                'finish_used_time|用户完成用时' =>  'require',
            ]);
            //不可重复提交
            $GroupActivityTaskUserResultModel = new GroupActivityTaskUserResultModel();
            $ResultInfo = $GroupActivityTaskUserResultModel->where([
                ['task_id','=',$param['task_id']],
                ['task_user_id','=',$param['task_user_id']??0],
                ['rating_scale_id','=',$param['rating_scale_id']],
                ['uid','=',$this->userData['id']],
            ])->find();
            if ($ResultInfo) throw new \Exception('不可重复提交！');
            $GroupActivityService = new GroupActivityService($this->app);
            if (!$GroupActivityService->generateReport([
                'company_id' => $this->userData['company_id'],//公司
                'areas_id' => $this->userData['areas_id'],//区域
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],//答题用户ID
                'task_id' => $param['task_id'],//任务ID
                'task_user_id' => $param['task_user_id']??0,//用户任务表ID
                'rating_scale_id' => $param['rating_scale_id'],//量表ID
                'userAnswer' => $param['question_answer']??[],//用户填写的答案
                'finish_used_time' => $param['finish_used_time'],//用户完成用时
            ],8))
                throw new \Exception($GroupActivityService->message);
            $GroupActivityTaskUserModel->commit();
            return success([
                'result_id' => $GroupActivityService->ResultId,
                'data' => $GroupActivityService->resultData,
                'is_valid' => $GroupActivityService->is_valid
            ],'提交成功！');
        } catch (\Exception $e) {
            $GroupActivityTaskUserModel->rollback();
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}